package com.supor.md_video.ui;

import android.app.Dialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseLocalConfigBean;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.md_video.R;
import com.supor.md_video.adapter.CommListAdapter;
import com.supor.md_video.databinding.FramgnetVideoCommBinding;
import com.supor.md_video.entity.VideoCommListBean;
import com.supor.md_video.entity.VideoCommListResultBean;
import com.supor.md_video.model.VideoListModel;
import com.supor.md_video.tools.NumberUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import autodispose2.AutoDispose;
import autodispose2.AutoDisposeConverter;
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider;
import io.reactivex.rxjava3.functions.Consumer;

public class VideoCommListDialog extends BottomSheetDialogFragment implements OnItemChildClickListener {

    private FramgnetVideoCommBinding framgnetVideoCommBinding;
    private VideoListModel videoListModel;
    private CommListAdapter commListAdapter;
    private String recipeId;
    private int videoPosition;
    private int currentPage;
    private int totalCommNum;

    public static VideoCommListDialog newInstance(String addrId, int videoPosition) {
        System.out.println("VideoCommListDialog_debug:  addrId+" + addrId + " videoPosition = " + videoPosition);
        VideoCommListDialog fragment = new VideoCommListDialog();
        Bundle bundle = new Bundle();
        bundle.putString("RECIPE_ID", addrId);
        bundle.putInt("VIDEO_POSITION", videoPosition);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置背景透明，才能显示出layout中诸如圆角的布局，否则会有白色底（框）
        setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.VideoCommDialogStyle);
        if (getArguments() != null) {
            recipeId = getArguments().getString("RECIPE_ID");
            videoPosition = getArguments().getInt("VIDEO_POSITION");

//            mUniquekey = getArguments().getString("uniquekey");
//            mUniquekey = "c322b12d56a3125e73e7b2978ff846c0";
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        framgnetVideoCommBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.framgnet_video_comm, container, false);
        return framgnetVideoCommBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        getDialog().setOnDismissListener(dialog -> {
            if (mOnDisMissCallBack != null) {
                mOnDisMissCallBack.onDismiss();
            }
            dismissAllowingStateLoss();
        });

        framgnetVideoCommBinding.rvCommLists.setLayoutManager(new LinearLayoutManager(getContext()));
        commListAdapter = new CommListAdapter();

        framgnetVideoCommBinding.rvCommLists.setAdapter(commListAdapter);

        framgnetVideoCommBinding.flClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismissAllowingStateLoss();
            }
        });
        framgnetVideoCommBinding.flInput.setOnClickListener(view1 -> {
            if (null == GlobalDataCache.userInfo || !AppAgent.isLogin()) {
//                ToastUtils.getInstance().showToast(getContext(), "请先登录");
                AppAgent.showLogin(false);
                dismiss();
                return;
            }
            CommInputDialog.newInstance(recipeId, recipeId, videoPosition)
                    .show(getChildFragmentManager(), "CommInputDialog");
        });
        commListAdapter.getLoadMoreModule().setEnableLoadMore(true);
        commListAdapter.getLoadMoreModule().setAutoLoadMore(true);
        commListAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
        commListAdapter.setOnItemChildClickListener(this);
//        commListAdapter.setOnItemClickListener(new OnItemClickListener() {
//            @Override
//            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
//                ToastUtils.getInstance().showToast(getContext(),"11111111111111");
//            }
//        });
        initData();
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        if (null != window) {
            WindowManager.LayoutParams params = window.getAttributes();
            params.gravity = Gravity.BOTTOM;
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.dimAmount = 0f;
            window.setAttributes(params);

            getDialog().setCancelable(true);
            getDialog().setCanceledOnTouchOutside(true);
        }

    }

    private void initData() {
        videoListModel = new ViewModelProvider(getActivity(),
                ViewModelProvider.AndroidViewModelFactory.getInstance(AppAgent.getApp())).get(VideoListModel.class);
        videoListModel.getVideoCommListResult().observe(this, new Observer<Result<VideoCommListResultBean>>() {
            @Override
            public void onChanged(Result<VideoCommListResultBean> videoCommListBeanResult) {
                if (null != videoCommListBeanResult.getData() && null != videoCommListBeanResult.getData().getRows()) {
                    commListAdapter.addData(videoCommListBeanResult.getData().getRows());
                    totalCommNum = videoCommListBeanResult.getData().getTotal();
                    framgnetVideoCommBinding.tvTitleCommNum.setText(totalCommNum + "条评论");
//                    framgnetVideoCommBinding.smartRefreshLayout.finishLoadMore();
                    if (commListAdapter.getData().size() >= videoCommListBeanResult.getData().getTotal()) {
//                        framgnetVideoCommBinding.smartRefreshLayout.setEnableLoadMore(false);
                        commListAdapter.getLoadMoreModule().loadMoreEnd();
                    } else {
                        commListAdapter.getLoadMoreModule().loadMoreComplete();
                    }
                } else {
//                    framgnetVideoCommBinding.smartRefreshLayout.setEnableLoadMore(false);
//                    framgnetVideoCommBinding.smartRefreshLayout.finishLoadMore(false);
//                    framgnetVideoCommBinding.smartRefreshLayout.setNoMoreData(true);
                    commListAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }
        });
        RxBus3.getInstance().register(Constants.TicPecipe.COMM_ADD, new Consumer<VideoCommListBean>() {
            @Override
            public void accept(VideoCommListBean videoCommListBean) throws Throwable {
                if (commListAdapter.getData().size() == 0) {
                    currentPage = 0;
                    videoListModel.loadVideoCommData(recipeId, ++currentPage, bindDestoryAutoDispose());
                } else {
                    commListAdapter.addData(0, videoCommListBean);
//                commListAdapter.getLoadMoreModule().loadMoreComplete();
                    framgnetVideoCommBinding.rvCommLists.smoothScrollToPosition(0);
                    framgnetVideoCommBinding.tvTitleCommNum.setText(++totalCommNum + "条评论");
                }
            }
        });
//        videoListModel.getVideoCommAddResult().observe(this, new Observer<Result<VideoCommListBean>>() {
//            @Override
//            public void onChanged(Result<VideoCommListBean> videoCommListBeanResult) {
//
//                commListAdapter.addData(0, videoCommListBeanResult.getData());
////                commListAdapter.getLoadMoreModule().loadMoreComplete();
//                framgnetVideoCommBinding.rvCommLists.smoothScrollToPosition(0);
//                framgnetVideoCommBinding.tvTitleCommNum.setText(++totalCommNum + "条评论");
//            }
//        });
        videoListModel.getCommThumbsResult().observe(this, new Observer<BaseLocalConfigBean>() {
            @Override
            public void onChanged(BaseLocalConfigBean baseLocalConfigBean) {
                if (null != baseLocalConfigBean
                        && commListAdapter.getData().size() > baseLocalConfigBean.getLocalPosition()) {
                    VideoCommListBean videoCommListBean = commListAdapter.getData().get(baseLocalConfigBean.getLocalPosition());
                    if (!videoCommListBean.getReplyId().equals(baseLocalConfigBean.getLocalId())) {
                        return;
                    }
                    videoCommListBean.setLikeId(baseLocalConfigBean.getLocalLikeId());
                    videoCommListBean.setLikeCount(videoCommListBean.getLikeCount() + baseLocalConfigBean.getLocalType());
                    videoCommListBean.setIsLike(baseLocalConfigBean.getLocalType() > 0
                            ? 1 : 2);
                    ImageView ivLike = (ImageView) commListAdapter
                            .getViewByPosition(baseLocalConfigBean.getLocalPosition(), R.id.iv_thumb_icon);
                    if (null != ivLike) {
                        ivLike.setBackgroundResource(videoCommListBean.getIsLike() == 1
                                ? R.mipmap.ic_thumbs_light : R.mipmap.ic_thumbs_gray);
                    }
                    TextView tvThumbNum = (TextView) commListAdapter
                            .getViewByPosition(baseLocalConfigBean.getLocalPosition(), R.id.tv_thumbs_num);
                    if (null != tvThumbNum) {
                        tvThumbNum.setText(NumberUtils.formatNum(videoCommListBean.getLikeCount()));
                        tvThumbNum.setTextColor(videoCommListBean.getIsLike() == 1 ? 0xffff9b00 : 0xff999999);
                    }
                }
            }
        });

        commListAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                videoListModel.loadVideoCommData(recipeId, ++currentPage, bindDestoryAutoDispose());
            }
        });

        currentPage = 0;
        videoListModel.loadVideoCommData(recipeId, ++currentPage, bindDestoryAutoDispose());
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        if (!passClick() || null == commListAdapter || commListAdapter.getData().size() <= position) {
            return;
        }
        if (view.getId() == R.id.ll_video_comm_thumb) {
            VideoCommListBean videoCommListBean = commListAdapter.getData().get(position);
            if (videoCommListBean.getIsLike() == 1) {
                videoListModel.commThumbsDel(videoCommListBean.getReplyId(), videoCommListBean.getLikeId(),
                        position, bindDestoryAutoDispose());
            } else {
                videoListModel.commThumbs(videoCommListBean.getReplyId(),
                        position,
                        bindDestoryAutoDispose());
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        RxBus3.getInstance().unregister(this.getClass());
    }

    public interface OnDisMissCallBack {
        void onDismiss();
    }

    private OnDisMissCallBack mOnDisMissCallBack;

    public void setOnDisMissCallBack(OnDisMissCallBack mOnDisMissCallBack) {
        this.mOnDisMissCallBack = mOnDisMissCallBack;
    }

    public <R> AutoDisposeConverter<R> bindAutoDispose() {
        return AutoDispose.autoDisposable(
                AndroidLifecycleScopeProvider.from(this)
        );
    }

    public <R> AutoDisposeConverter<R> bindDestoryAutoDispose() {
        return AutoDispose.autoDisposable(
                AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)
        );
    }

    private long lastClick;

    /**
     * [防止快速点击]
     *
     * @return
     */
    public boolean passClick() {
        if (System.currentTimeMillis() - lastClick <= 1000) {
            return false;
        }
        lastClick = System.currentTimeMillis();
        return true;
    }

    @Override
    public void dismiss() {
        super.dismissAllowingStateLoss();
    }

}